from datetime import datetime

import bcrypt
import pymysql
from flask import jsonify, render_template, request, current_app, abort
from config.config import DB_CONFIG
from werkzeug.utils import secure_filename
import os
from config.config import url
import time


class Picture:
    def __init__(self, app):
        self.app = app
        self.app.add_url_rule('/api/get_pictures', view_func=self.get_pictures, methods=['GET'])
        self.app.add_url_rule('/api/get_shop', view_func=self.get_shop, methods=['GET'])
        self.app.add_url_rule('/api/get_isGroom', view_func=self.get_isGroom, methods=['GET'])
        self.app.add_url_rule('/api/get_categoryName', view_func=self.get_categoryName, methods=['GET'])
        self.app.add_url_rule('/api/show_select', view_func=self.show_select, methods=['GET'])
        self.app.add_url_rule('/api/upload_shop', view_func=self.upload_shop, methods=['POST'])
        self.app.add_url_rule('/api/show_all', view_func=self.show_all, methods=['GET'])
        self.app.add_url_rule('/api/get_total_count', view_func=self.get_total_count, methods=['GET'])
        self.app.add_url_rule('/api/show_my_products', view_func=self.show_my_products, methods=['GET'])
        self.app.add_url_rule('/api/show_my_products_delete', view_func=self.delete_product, methods=['DELETE'])
        self.app.add_url_rule('/api/delete_save', view_func=self.delete_save, methods=['POST'])
        self.app.add_url_rule('/api/update_product', view_func=self.update_product, methods=['POST'])
        self.app.add_url_rule('/api/show_my_products1', view_func=self.show_my_products1, methods=['GET'])
        self.app.add_url_rule('/api/show_details', view_func=self.show_details, methods=['GET'])
        self.app.add_url_rule('/api/collection', view_func=self.collection, methods=['POST'])
        self.app.add_url_rule('/api/get_collection', view_func=self.get_collection, methods=['GET'])
        self.app.add_url_rule('/api/delete_collection', view_func=self.delete_collection, methods=['POST'])
        self.app.add_url_rule('/api/my_collection', view_func=self.my_collection, methods=['GET'])
        self.app.add_url_rule('/api/get_shop_id', view_func=self.get_shop_id, methods=['GET'])
        self.app.add_url_rule('/api/cart', view_func=self.cart, methods=['POST'])
        self.app.add_url_rule('/api/get_cart', view_func=self.get_cart, methods=['GET'])
        self.app.add_url_rule('/api/delete_cart', view_func=self.delete_cart, methods=['POST'])
        self.app.add_url_rule('/api/my_cart', view_func=self.my_cart, methods=['GET'])
        self.app.add_url_rule('/api/get_shop_id1', view_func=self.get_shop_id1, methods=['GET'])
        self.app.add_url_rule('/api/get_shop_revise', view_func=self.get_shop_revise, methods=['GET'])
        self.app.add_url_rule('/api/update_shop_revise', view_func=self.update_shop_revise, methods=['POST'])
    def get_db_connection(self):
        return pymysql.connect(**DB_CONFIG)

    def get_url(self):
        return url

    def show_details(self):
        # 从cookies中获取用户名和令牌
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")
        product_id = request.args.get('id', '')
        if product_id:
            conn = self.get_db_connection()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            sql = """
            SELECT Products.ProductName, userinfo.username, Products.Price, Products.ImageURL,Products.image_two, Products.image_three, Products.image_four, Products.image_five, Products.image_six,  Products.Description, Products.Condition, Products.PostedDate, userinfo.Credits
            FROM Products
            INNER JOIN userinfo ON Products.OwnerID = userinfo.UID
            WHERE Products.ProductID = %s
            """
            cursor.execute(sql, (product_id,))
            product_details = cursor.fetchone()
            print(product_id)
            cursor.close()
            conn.close()
            if product_details:
                return jsonify({'status': 'success', 'data': product_details})
            else:
                return jsonify({'status': 'fail', 'message': 'No product found with the given ID.'})
        else:
            return jsonify({'status': 'fail', 'message': 'No product ID provided.'})

    def get_shop(self):
        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute(
                "SELECT products.*, userinfo.username FROM products "
                "JOIN userinfo ON products.OwnerID = userinfo.UID "
                "WHERE products.IsGroom = 1 and products.IsSold = 0 "
                "ORDER BY products.PostedDate ASC"
            )
            products = cursor.fetchall()
            return jsonify({'status': 'success', 'data': products, 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    def get_isGroom(self):
        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute(
                "SELECT username, Credits, img, nikename, register_time FROM userinfo WHERE IsGroom = 1"
            )
            users = cursor.fetchall()
            return jsonify({'status': 'success', 'data': users, 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    def get_categoryName(self):
        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute("SELECT CategoryName FROM ProductCategories")
            categories = cursor.fetchall()
            return jsonify({'status': 'success', 'data': categories})
        finally:
            cursor.close()
            conn.close()

    def show_select(self):
        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            searchText = request.args.get('searchText', '')
            query = (
                "SELECT products.ProductID, products.Price, products.ImageURL, products.Description, products.IsSold, products.ProductName, products.Category, userinfo.username,userinfo.Credits "
                "FROM products "
                "JOIN userinfo ON products.OwnerID = userinfo.UID "
                "WHERE products.ProductName LIKE %s AND products.IsSold = 0 "
                "ORDER BY products.PostedDate ASC "
            )
            cursor.execute(query, ('%' + searchText + '%',))
            products = cursor.fetchall()
            return jsonify({'status': 'success', 'data': products})
        finally:
            cursor.close()
            conn.close()
    def upload_shop(self):
        # 从cookies中获取用户名和令牌
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            # 从请求中获取表单数据
            product_name = request.form.get('productName')
            price = request.form.get('price')
            description = request.form.get('description')
            condition = request.form.get('condition')
            category = request.form.get('category')

            # 查询数据库以获取UID
            cursor.execute("SELECT UID FROM userinfo WHERE username = %s", (username,))
            result = cursor.fetchone()
            if result is None:
                return jsonify({'status': 'error', 'msg': '用户不存在'})

            owner_id = result['UID']

            # 从请求中获取图片文件
            image_files = [request.files.get('image' + str(i)) for i in range(1, 7)]
            image_urls = []

            for i, image_file in enumerate(image_files, start=1):
                if image_file:
                    timestamp = str(int(time.time()) + i)  # 获取当前时间戳并转换为字符串，然后加上i
                    filename = secure_filename(timestamp + os.path.splitext(image_file.filename)[1])  # 使用时间戳作为文件名
                    image_path = os.path.join(current_app.root_path, 'static/images/userimg/shop', filename)
                    image_file.save(image_path)
                    image_urls.append('/static/images/userimg/shop/' + filename)
                else:
                    image_urls.append(None)

            # 插入数据到Products表
            cursor.execute(
                "INSERT INTO Products (ProductName, OwnerID, Price, ImageURL, Description, `Condition`, Category, PostedDate, IsSold, IsGroom, image_two, image_three, image_four, image_five, image_six) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), 0, 0, %s, %s, %s, %s, %s)",
                (product_name, owner_id, price, image_urls[0], description, condition, category, *image_urls[1:])
            )
            conn.commit()

            return jsonify({'status': 'success', 'msg': '商品上传成功'})
        finally:
            cursor.close()
            conn.close()

    def get_pictures(self):
        """获取所有状态为1的轮播图片"""
        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute(
                "SELECT * FROM yesapi_xbinstore_tb_index_slide_ad WHERE yesapi_xbinstore_tb_index_slide_ad_status = 1 ORDER BY sort_order ASC")
            pictures = cursor.fetchall()
            return jsonify({'status': 'success', 'data': pictures})
        finally:
            cursor.close()
            conn.close()

    def get_total_count(self):  # 从cookies中获取用户名和令牌
        # username = request.cookies.get('username')
        # token = request.cookies.get('token')
        #
        # # 检查用户名和令牌是否存在
        # if not username or not token:
        #     abort(402, description="未授权：缺少用户名或令牌")
        #
        # # 检查令牌是否有效
        # conn = self.get_db_connection()
        # cursor = conn.cursor()
        # cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        # results = cursor.fetchall()
        # cursor.close()
        # conn.close()
        #
        # # 遍历查询结果，检查是否有匹配的token
        # for result in results:
        #     if result[0] == token:
        #         break
        # else:
        #     abort(403, description="未授权：无效的令牌")

        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            cursor.execute(
                "SELECT COUNT(*) as total FROM products"
            )
            result = cursor.fetchone()
            return jsonify({'status': 'success', 'data': result['total'], 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    def show_all(self):  # 从cookies中获取用户名和令牌
        # username = request.cookies.get('username')
        # token = request.cookies.get('token')
        #
        # # 检查用户名和令牌是否存在
        # if not username or not token:
        #     abort(402, description="未授权：缺少用户名或令牌")
        #
        # # 检查令牌是否有效
        # conn = self.get_db_connection()
        # cursor = conn.cursor()
        # cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        # results = cursor.fetchall()
        # cursor.close()
        # conn.close()
        #
        # # 遍历查询结果，检查是否有匹配的token
        # for result in results:
        #     if result[0] == token:
        #         break
        # else:
        #     abort(403, description="未授权：无效的令牌")

        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            page = int(request.args.get('page', 1))
            per_page = 9
            offset = (page - 1) * per_page
            cursor.execute(
                "SELECT products.*, userinfo.username, userinfo.Credits FROM products "
                "JOIN userinfo ON products.OwnerID = userinfo.UID "
                "ORDER BY products.IsSold ASC, products.PostedDate ASC "
                "LIMIT %s OFFSET %s",
                (per_page, offset)
            )
            products = cursor.fetchall()
            return jsonify({'status': 'success', 'data': products, 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    def show_my_products(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            page = int(request.args.get('page', 1))
            per_page = 9
            offset = (page - 1) * per_page
            cursor.execute(
                "SELECT products.*, userinfo.username FROM products "
                "JOIN userinfo ON products.OwnerID = userinfo.UID "
                "WHERE userinfo.username = %s "
                "ORDER BY products.IsSold ASC, products.PostedDate ASC "
                "LIMIT %s OFFSET %s",
                (username, per_page, offset)
            )
            products = cursor.fetchall()
            return jsonify({'status': 'success', 'data': products, 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    # 修改接口
    def show_my_products1(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        conn = self.get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        try:
            product_id = request.args.get('product_id')  # 从请求参数中获取产品ID
            cursor.execute(
                "SELECT products.*, userinfo.username FROM products "
                "JOIN userinfo ON products.OwnerID = userinfo.UID "
                "WHERE userinfo.username = %s AND products.ProductID = %s",  # 根据产品ID查询对应的产品信息
                (username, product_id)
            )
            product = cursor.fetchone()  # 获取单个产品信息
            return jsonify({'status': 'success', 'data': product, 'code': 200, 'msg': '查询成功'})
        finally:
            cursor.close()
            conn.close()

    def delete_product(self):
        product_id = request.args.get('product_id')
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        # 删除商品记录
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("DELETE FROM products WHERE ProductID = %s", (product_id,))
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'msg': '商品删除成功', 'code': 200})

    def delete_save(self):
        username1 = request.cookies.get('username')
        token1 = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username1 or not token1:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username1,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token1:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        product_id = data.get('product_id')

        # 检查用户名和密码是否存在
        if not username or not password or not product_id:
            return jsonify({'status': 'error', 'msg': '用户名、密码或商品ID为空'})

        # 验证用户名和密码
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute('SELECT `password` FROM `userinfo` WHERE `username` = %s', (username,))
        result = cursor.fetchone()
        if result is None:
            return jsonify({'status': 'error', 'msg': '用户名不存在'})
        stored_password = result[0].encode('utf-8')
        if not bcrypt.checkpw(password.encode('utf-8'), stored_password):
            return jsonify({'status': 'error', 'msg': '密码错误'})

        # 删除商品记录
        cursor.execute("DELETE FROM products WHERE ProductID = %s", (product_id,))
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'msg': '商品删除成功'})

    def update_product(self):
        # 从cookies中获取用户名和令牌
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        # 从请求中获取表单数据
        product_id = request.form.get('productID')
        product_name = request.form.get('productName')
        price = request.form.get('price')
        description = request.form.get('description')
        condition = request.form.get('condition')
        category = request.form.get('category')

        # 从请求中获取图片文件
        image_files = [request.files.get('image' + str(i)) for i in range(1, 7)]
        image_urls = []

        for i, image_file in enumerate(image_files, start=1):
            if image_file:
                timestamp = str(int(time.time()) + i)  # 获取当前时间戳并转换为字符串，然后加上i
                filename = secure_filename(timestamp + os.path.splitext(image_file.filename)[1])  # 使用时间戳作为文件名
                image_path = os.path.join(current_app.root_path, 'static/images/userimg/shop', filename)
                image_file.save(image_path)
                image_urls.append('/static/images/userimg/shop/' + filename)
            else:
                image_urls.append(None)

        # 更新商品记录
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE Products SET ProductName = %s, Price = %s, ImageURL = %s, Description = %s, `Condition` = %s, Category = %s, image_two = %s, image_three = %s, image_four = %s, image_five = %s, image_six = %s WHERE ProductID = %s",
            (product_name, price, image_urls[0], description, condition, category, *image_urls[1:], product_id)
        )
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'msg': '商品信息更新成功'})

    def collection(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.form.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(
                "INSERT INTO `Collection` (`username`, `ID`) VALUES (%s, %s)",
                (username, product_id)
            )
            conn.commit()
            return jsonify({'status': 'success', 'message': '收藏成功'})
        except Exception as e:
            conn.rollback()
            return jsonify({'status': 'fail', 'message': '服务器错误：' + str(e)})
        finally:
            cursor.close()
            conn.close()

    def delete_collection(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.form.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(
                "DELETE FROM `Collection` WHERE `username` = %s AND `ID` = %s",
                (username, product_id)
            )
            conn.commit()
            return jsonify({'status': 'success', 'message': '取消收藏成功'})
        except Exception as e:
            conn.rollback()
            return jsonify({'status': 'fail', 'message': '服务器错误：' + str(e)})
        finally:
            cursor.close()
            conn.close()

    def get_collection(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.args.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "SELECT * FROM `Collection` WHERE `username` = %s AND `ID` = %s",
            (username, product_id)
        )
        result = cursor.fetchone()
        cursor.close()
        conn.close()

        if result:
            return jsonify({'status': 'success', 'message': '已收藏'})
        else:
            return jsonify({'status': 'fail', 'message': '未收藏'})

    def my_collection(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        if not username:
            cursor.close()
            conn.close()
            abort(403, description="未授权：缺少用户名")

        cursor.execute("SELECT ID FROM Collection WHERE username = %s", (username,))
        product_ids = cursor.fetchall()

        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'data': product_ids})

    def get_shop_id(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        product_id = request.args.get('id')
        if not product_id:
            cursor.close()
            conn.close()
            abort(400, description="错误请求：缺少商品ID")

        cursor.execute(
            "SELECT Products.ProductName, Products.ImageURL, Products.Price, Products.Description, userinfo.username, userinfo.Credits ,products.IsSold FROM Products INNER JOIN userinfo ON Products.OwnerID = userinfo.UID WHERE Products.ProductID = %s",
            (product_id,))
        product = cursor.fetchone()

        cursor.close()
        conn.close()

        if not product:
            abort(404, description="未找到：商品不存在")

        return jsonify({'status': 'success', 'data': product})

    def cart(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.form.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(
                "INSERT INTO `cart` (`username`, `ID`) VALUES (%s, %s)",
                (username, product_id)
            )
            conn.commit()
            return jsonify({'status': 'success', 'message': '收藏成功'})
        except Exception as e:
            conn.rollback()
            return jsonify({'status': 'fail', 'message': '服务器错误：' + str(e)})
        finally:
            cursor.close()
            conn.close()

    def delete_cart(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.form.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(
                "DELETE FROM `cart` WHERE `username` = %s AND `ID` = %s",
                (username, product_id)
            )
            conn.commit()
            return jsonify({'status': 'success', 'message': '取消收藏成功'})
        except Exception as e:
            conn.rollback()
            return jsonify({'status': 'fail', 'message': '服务器错误：' + str(e)})
        finally:
            cursor.close()
            conn.close()

    def get_cart(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()
        cursor.close()
        conn.close()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            abort(403, description="未授权：无效的令牌")

        product_id = request.args.get('id')

        # 检查用户名和商品 ID 是否存在
        if not username or not product_id:
            return jsonify({'status': 'fail', 'message': '用户名或商品 ID 为空'})

        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "SELECT * FROM `cart` WHERE `username` = %s AND `ID` = %s",
            (username, product_id)
        )
        result = cursor.fetchone()
        cursor.close()
        conn.close()

        if result:
            return jsonify({'status': 'success', 'message': '已收藏'})
        else:
            return jsonify({'status': 'fail', 'message': '未收藏'})

    def my_cart(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        if not username:
            cursor.close()
            conn.close()
            abort(403, description="未授权：缺少用户名")

        cursor.execute("SELECT ID FROM cart WHERE username = %s", (username,))
        product_ids = cursor.fetchall()

        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'data': product_ids})

    def get_shop_id1(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        product_id = request.args.get('id')
        if not product_id:
            cursor.close()
            conn.close()
            abort(400, description="错误请求：缺少商品ID")

        cursor.execute(
            "SELECT Products.ProductName, Products.ImageURL, Products.Price, Products.Description, userinfo.username, userinfo.Credits ,products.IsSold FROM Products INNER JOIN userinfo ON Products.OwnerID = userinfo.UID WHERE Products.ProductID = %s",
            (product_id,))
        product = cursor.fetchone()

        cursor.close()
        conn.close()

        if not product:
            abort(404, description="未找到：商品不存在")

        return jsonify({'status': 'success', 'data': product})

    def get_shop_revise(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        product_id = request.args.get('id')
        if not product_id:
            cursor.close()
            conn.close()
            abort(400, description="错误请求：缺少商品ID")

        cursor.execute(
            "SELECT ProductName, Price, ImageURL, Description, `Condition`, Category, image_two, image_three, image_four, image_five, image_six, ProductID FROM Products WHERE ProductID = %s",
            (product_id,))
        product = cursor.fetchone()

        cursor.close()
        conn.close()

        if not product:
            abort(404, description="未找到：商品不存在")

        return jsonify({'status': 'success', 'data': product})

    def update_shop_revise(self):
        username = request.cookies.get('username')
        token = request.cookies.get('token')

        # 检查用户名和令牌是否存在
        if not username or not token:
            abort(402, description="未授权：缺少用户名或令牌")

        # 检查令牌是否有效
        conn = self.get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT `token` FROM `token` WHERE `username` = %s", (username,))
        results = cursor.fetchall()

        # 遍历查询结果，检查是否有匹配的token
        for result in results:
            if result[0] == token:
                break
        else:
            cursor.close()
            conn.close()
            abort(403, description="未授权：无效的令牌")

        # 从请求中获取商品ID和新的商品信息
        product_id = request.form.get('id')
        product_name = request.form.get('productName')
        price = request.form.get('price')
        image_url = request.form.get('imageURL')
        description = request.form.get('description')
        condition = request.form.get('condition')
        category = request.form.get('category')
        image_two = request.form.get('image_two')
        image_three = request.form.get('image_three')
        image_four = request.form.get('image_four')
        image_five = request.form.get('image_five')
        image_six = request.form.get('image_six')

        # 更新商品记录
        cursor.execute(
            "UPDATE Products SET ProductName = %s, Price = %s, ImageURL = %s, Description = %s, `Condition` = %s, Category = %s, image_two = %s, image_three = %s, image_four = %s, image_five = %s, image_six = %s WHERE ProductID = %s",
            (product_name, price, image_url, description, condition, category, image_two, image_three, image_four,
             image_five, image_six, product_id)
        )
        conn.commit()
        cursor.close()
        conn.close()

        return jsonify({'status': 'success', 'msg': '商品信息更新成功',"code":product_name})

